<template>
  <div class="photo">
      <div class="photo-box">
          <canvas id="photoCa" width="375" height="380"></canvas>
      </div>
      <button class="save-btn" @click="drawImage">绘制</button>
      <a class="save-btn" href="" download="test" id="download">保存</a>
  </div>
</template>

<script>
const bgImg = require('../assets/images/bg.jpeg')
const headImg = require('../assets/images/head.jpeg')
const bannerImg = require('../assets/images/banner.jpeg')
export default {
  data () {
    return {
      canvasEle: null,
      context: null,
      downloadBtn: null
    }
  },
  mounted () {
    this.initPhtot()
  },
  methods: {
    initPhtot () {
      this.canvasEle = document.querySelector('#photoCa')
      this.context = this.canvasEle.getContext('2d')
      this.downloadBtn = document.querySelector('#download')
    },
    async drawImage () {
      let bg = new Image()
      let head = new Image()
      let banner = new Image()
      bg.src = bgImg
      banner.src = bannerImg
      head.src = headImg
      //   bg.onload = () => {
      //     this.context.drawImage(bg, 0, 0, 375, 380)
      //     banner.onload = () => {
      //       this.context.drawImage(banner, 0, 0, 375, 288)
      //       head.onload = () => {
      //         console.log('head')
      //         this.context.drawImage(head, 300, 245, 65, 65)
      //         this.getDataBase64()
      //       }
      //     }
      //   }
      await this.drawPromise(bg)
      await this.context.drawImage(bg, 0, 0, 375, 380)
      await this.drawPromise(banner)
      await this.context.drawImage(banner, 0, 0, 375, 288)
      await this.drawPromise(head)
      await this.context.drawImage(head, 300, 245, 65, 65)
      this.getDataBase64()
    },
    drawPromise (ele) {
      return new Promise((resolve, reject) => {
        ele.onload = () => {
          resolve()
        }
      })
    },
    getDataBase64 () {
      this.canvasEle.toBlob(blob => {
        var url = URL.createObjectURL(blob)
        this.downloadBtn.setAttribute('href', url)
      })
    }
  }
}
</script>

<style lang='scss' scoped>
#photoCa{
    border: 1px solid #eee;
}
.save-btn{
    display: inline-block;
    width: 88px;
    height: 36px;
    background: #86b0ed;
    border: 0;
    border-radius: 4px;
    margin-right: 20px;
    line-height: 36px;
    text-align: center;
    color: #fff;
    font-size: 14px;
    text-decoration: none;
    outline: none;
    vertical-align: middle;
}
</style>
